import Express from "express";
import chalk from "chalk";
import inquirer from "inquirer";
import Path from "path";
// @ts-ignore
import { createProxyMiddleware } from "http-proxy-middleware";
import { pathExistsSync, ensureDirSync } from "fs-extra";
import crossPortKill from "cross-port-killer";
/**
 * 启动electron server服务器
 */
export function start() {
  const electronProxy = createProxyMiddleware({
    target: "https://registry.npmmirror.com",
    changeOrigin: true,
    ws: true,
    pathRewrite: (path: string) => {
      console.log(path);
      return path.replace(/\/electron\/v?/, "/electron/v");
    },
  });
  const app = Express();
  app.use(electronProxy);
  app.listen(80);
  console.log(`--electron_mirror http://localhost/-/binary/electron/`);
  console.log(`--CYPRESS_DOWNLOAD_MIRROR http://localhost/-/binary/cypress/`);
}

/**
 * 启动electron mirror服务器，需要手动下载好electron镜像
 */
export async function server() {
  let app = Express();
  let options = await inquirer.prompt({
    name: "path",
    message: "Where do you want to save the mirrors? ",
    default: "D:/.mirrors",
    validate(_input) {
      console.log(_input);
      try {
        ensureDirSync(_input);
        if (pathExistsSync(_input)) {
          return true;
        } else {
          return "Invalid path";
        }
      } catch (error) {
        return "Invalid path";
      }
    },
  });
  console.log(
    chalk.greenBright(
      `You can now download electron** and put it directly under: (with no deeper directories)`
    )
  );
  console.log(chalk.bgBlueBright(options.path));
  console.log(
    `Note: electron** can be downloaded from https://npmmirror.com/mirrors/electron/`
  );
  console.log("now run everything with");
  console.log(
    chalk.bgBlueBright(`--electron_mirror http://localhost/electron`)
  );
  console.log(
    chalk.bgBlueBright(`electron_mirror "http://localhost/electron"`),
    "\t in .yarnrc"
  );
  // https://registry.npmmirror.com/-/binary/electron/18.2.4/electron-v18.2.4-win32-x64.zip
  app.use("*", (req, res, next) => {
    let { baseUrl } = req;
    let file = baseUrl.split(/[/\\]/).pop();
    let path = Path.join(
      options.path,
      // @ts-ignore
      file
    );
    if (pathExistsSync(path)) {
      console.log(path);
      res.sendFile(path, (...args) => {
        console.log(args);
      });
    } else {
      console.log(chalk.redBright(`Unable to resolve: ${baseUrl}`));
      console.log(chalk.redBright(`Require: ${path}`));
      // res.status(500).end();
      next();
    }
  });
  app.use(
    createProxyMiddleware({
      target: "https://registry.npmmirror.com/-/binary",
      changeOrigin: true,
      ws: true,
    })
  );
  try {
    await crossPortKill(80);
  } finally {
    app.listen(80);
  }
  return app;
}
